package com.woyou.ui.activity.orderlist;

import java.util.ArrayList;
import java.util.List;

import retrofit.RetrofitError;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.OnPreRefreshingAnimListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.woyou.BroadcastConstant;
import com.woyou.bean.Info;
import com.woyou.bean.MyOrderItem;
import com.woyou.bean.Result;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.MyOrderReq;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.activity.BaseActivity;
import com.woyou.ui.activity.HomeActivity_;
import com.woyou.ui.activity.LoginActivity_;
import com.woyou.ui.activity.orderdetail.OrderDetailActivity;
import com.woyou.ui.activity.orderlist.MultipleStatusItemView.ILoadOrderDetailListener;
import com.woyou.ui.adapter.MyOrderAdapter;
import com.woyou.ui.adapter.MyOrderAdapter.RefreshOrderListImp;
import com.woyou.ui.api.RefreshOrderDetailsListener;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.fragment.AssessmentOrderLayout;
import com.woyou.ui.fragment.ConReceivTimeOrder;
import com.woyou.ui.fragment.ShopsFragment_;
import com.woyou.utils.Task;

/**
 * 我的订单
 * 
 * @author shenzhou 2015年1月5日
 */
public class MyOrderActivity extends BaseActivity {

	private PullToRefreshListView orderListView;
	private ErrorHintView mErrorHintView;
	private ConReceivTimeOrder conReceivTimeOrder;
	private AssessmentOrderLayout assessmentLayout;

	/** 显示订单列表 **/
	private int VIEW_ORDER = 1;
	/** 显示断网 **/
	private int VIEW_WIFIFAILUER = 2;
	/** 显示加载数据失败 **/
	private int VIEW_LOADFAILURE = 3;
	/** 显示加载中 **/
	private int VIEW_LOADING = 4;
	/** 显示请求超时 **/
	private int VIEW_OUTTIME = 5;
	/** 显示没有数据 **/
	private int VIEW_NOORDERS = 6;

	private MyOrderAdapter myOrderAdapter;
	private List<MyOrderItem> myOrders = new ArrayList<MyOrderItem>(); // ListView的数据源
	private UserInfo info; // 用户信息

	private String originClassName; // 来源的activity
	private MyOrderActController mActController;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fm_myorder);

		mActController = new MyOrderActController(mContext, this);
		registerBrocast();

		initView();
		initEvent();
		setUpPullToRefreshList();
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void onResume() {
		super.onResume();
		if (hasInfo()) {
			Class originClzz = mInfo.getOriginClzz();
			if (originClzz != null) {
				originClassName = originClzz.getName();
			}
		}
		defParameter();
		info = mUserModel.getUserInfo();
		if (footerView != null) {
			orderListView.getRefreshableView().removeFooterView(footerView);
			footerView = null;
		}
		showViewById(VIEW_LOADING);
		refreshData(true);
	}

	private LinearLayout footerView; // 最后一条listview

	/**
	 * 配置下拉刷新控件
	 * 
	 * @return
	 */
	private void setUpPullToRefreshList() {
		orderListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if (refreshView.isHeaderShown()) {
					defParameter();
					myOrders.clear();
					refreshData(true);
				}
			}
		});

		orderListView
				.setOnPreRefreshingAnimListener(new OnPreRefreshingAnimListener() {
					@Override
					public void onPreRefreshingAnim() {
						orderListView.setFooterLoadingViewHeaderText("加载更多订单");
					}
				});

		orderListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
					@Override
					public void onLastItemVisible() {
						if (pageNext == 0) {
							// 没有下一页了
							orderListView.onRefreshComplete();
							if (footerView == null) {
								footerView = (LinearLayout) View.inflate(
										mContext,
										R.layout.item_pull_to_refresh_footer,
										null);
								TextView footer = (TextView) footerView
										.findViewById(R.id.footer);
								// footer.setText("到底了呢-共" + orderList.size() +
								// "条订单");
								footer.setText("到底了呢");
								orderListView.getRefreshableView()
										.addFooterView(footerView);
							}
						} else {
							// 滑动到底部自动刷新
							refreshData(false);
						}
					}
				});
	}

	private void initEvent() {
		if (assessmentLayout != null) {
			assessmentLayout.setListener(new RefreshOrderDetailsListener() {
				@Override
				public void callBack(String orderId) {
					defParameter();
					showViewById(VIEW_LOADING);
					refreshData(true);
				}
			});
		}

		if (conReceivTimeOrder != null) {
			conReceivTimeOrder.setListener(new RefreshOrderDetailsListener() {
				@Override
				public void callBack(String orderId) {
					defParameter();
					showViewById(VIEW_LOADING);
					refreshData(true);
				}
			});
		}

	}

	private void initView() {
		orderListView = (PullToRefreshListView) findViewById(R.id.myorder_listview);
		findViewById(R.id.myorder_back).setOnClickListener(this);
		mErrorHintView = (ErrorHintView) findViewById(R.id.hintView);
		conReceivTimeOrder = (ConReceivTimeOrder) findViewById(R.id.confirm_order);
		assessmentLayout = (AssessmentOrderLayout) findViewById(R.id.assessment_order);

		if (myOrderAdapter == null) {
			myOrderAdapter = new MyOrderAdapter(myOrders, mActivity,
					new RefreshOrderListImp() {
						@Override
						public void refreshOrder() {
							myOrders.clear();
							defParameter();
							showViewById(VIEW_LOADING);
							refreshData(true);
						}
					}, new ILoadOrderDetailListener() {
						
						@Override
						public void loadOrderDetail(MyOrderItem orderItem) {
							mActController.loadOrderDetail(orderItem.getoId());
						}
					});
		}
		orderListView.setAdapter(myOrderAdapter);

		orderListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				MyOrderItem order = myOrders.get(position - 1);
				if (order.getState()==1) // 新订单、推送成功、未接通
					return;
				if (TextUtils.isEmpty(order.getoId()))
					return;

				Info<MyOrderItem> info = new Info<MyOrderItem>();
				info.setData(order);
				info.setOrigin(MyOrderActivity.class);
				openActivity(OrderDetailActivity.class, info);
			}

		});
	}

	private int pageNext = 1; // 下一页页码
	private MyOrderReq myOrderReq = new MyOrderReq();
	private Result<List<MyOrderItem>> result = null;

	private void refreshData(boolean clean) {
		lastTask = new RefreshDataTask(lastTask.getID() + 1, clean);
		executeTask(lastTask);
	}

	/**
	 * 丢弃老数据重新刷新
	 * 
	 * @author longtao.li
	 * 
	 */
	class RefreshDataTask extends Task {

		boolean clean = false; // 是否清空原数据

		public RefreshDataTask(int id, boolean flag) {
			super(id);
			this.clean = flag;
		}

		@Override
		public void run() {
			if (!NetWorkCenter.isNetworkConnected(getBaseContext())) { // 断网
				runOnUI(new Runnable() {
					@Override
					public void run() {
						showViewById(VIEW_WIFIFAILUER);
						return;
					}
				});
			}
			runOnUI(new Runnable() {

				public void run() {
					if (footerView != null) {
						orderListView.getRefreshableView().removeFooterView(
								footerView);
						footerView = null;
					}
				}
			});

			try {
				myOrderReq.setuId(info.getuId()); // 用户名
				myOrderReq.setPwd(info.getPwd()); // 用户密码
				myOrderReq.setPage(pageNext); // 下一页页码
				result = mUserModel.v2_3queryMyOrder(myOrderReq);
			} catch (RetrofitError e) {
				switch (e.getKind()) {
				case HTTP:
					showViewById(VIEW_OUTTIME);
					return;
				case CONVERSION:
					showViewById(VIEW_LOADFAILURE);
					return;
				case NETWORK:
					showViewById(VIEW_OUTTIME);
					return;
				case UNEXPECTED:
					showViewById(VIEW_LOADFAILURE);
					return;
				}
			} finally {
				runOnUI(new Runnable() {
					public void run() {
						orderListView.onRefreshComplete();
					}
				});
			}

			// 判断是不是用户的最后操作,最后任务的ID如果比此任务的ID大则丢弃请求结果
			if (getID() < lastTask.getID()) {
				return;
			}

			if (result != null && result.code == 1) {
				refreshUI(result, clean);
			} else if (result != null && result.code == -3) {
				runOnUI(new Runnable() {
					@Override
					public void run() {
						hideLoading();
						showToast(result.getMsg());
						openActivity(LoginActivity_.class, null);
						finish();
					}
				});
			} else {
				showViewById(VIEW_LOADFAILURE);
			}
		}

	}

	private List<MyOrderItem> orderList = new ArrayList<MyOrderItem>(); // 一共有多少订单

	private void refreshUI(final Result<List<MyOrderItem>> result,
			final boolean clean) {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				if (clean) {
					myOrders.clear();
					orderList.clear();
				}
				List<MyOrderItem> list = result.getData();
				if (list != null && list.size() > 0) {
					orderList.addAll(list);
					myOrders.addAll(list);
					pageNext = result.getPage();
					// 添加订单分隔线的bean
					mActController.addOrderSeparator(myOrders);

				}
				if (orderList == null || orderList.size() == 0) {
					showViewById(VIEW_NOORDERS);
				} else {
					myOrderAdapter.notifyDataSetChanged();
					showViewById(VIEW_ORDER);
					if (clean) {
						orderListView.getRefreshableView().setSelection(0);
					}

				}
			}
		});
	}

	/**
	 * 显示订单列表：1 显示断网：2 显示加载数据失败：3 显示加载中：4 显示请求超时：5 显示没有数据：6
	 */
	private void showViewById(final int i) {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				mErrorHintView.setVisibility(View.GONE);
				orderListView.setVisibility(View.GONE);
				switch (i) {
				case 1:
					mErrorHintView.hideLoading();
					orderListView.setVisibility(View.VISIBLE);
					break;
				case 2:
					mErrorHintView.hideLoading();
					mErrorHintView.netError(new OperateListener() {
						@Override
						public void operate() {
							showViewById(VIEW_LOADING);
							refreshData(true);
						}
					});
					break;
				case 3:
					mErrorHintView.hideLoading();
					mErrorHintView.loadFailure(new OperateListener() {
						@Override
						public void operate() {
							showViewById(VIEW_LOADING);
							refreshData(true);
						}
					});
					break;
				case 4:
					mErrorHintView.loadingData();
					break;
				case 5:
					mErrorHintView.hideLoading();
					mErrorHintView.timeOut(new OperateListener() {
						@Override
						public void operate() {
							showViewById(VIEW_LOADING);
							refreshData(true);
						}
					});
					break;
				case 6:
					mErrorHintView.hideLoading();
					mErrorHintView.noOrder(new OperateListener() {
						@SuppressWarnings("rawtypes")
						@Override
						public void operate() {
							Info<Class> info = new Info<Class>();
							info.setData(ShopsFragment_.class);
							openActivity(HomeActivity_.class, info);
							finish();
						}
					});
					break;
				}
			}
		});
	}

	/**
	 * 默认搜索数据
	 */
	private void defParameter() {
		pageNext = 1;
	}

	/* 注册广播 */
	private void registerBrocast() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(BroadcastConstant.NOTIFY_ACT_ASSESSMENT_ORDER);
		filter.addAction(BroadcastConstant.NOTIFY_ACT_CONFIRM_DELIVER);
		mContext.registerReceiver(mReceiver, filter);
	}

	private void unregisterBrocast() {
		if (mReceiver != null) {
			mContext.unregisterReceiver(mReceiver);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterBrocast();
	}

	BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(BroadcastConstant.NOTIFY_ACT_ASSESSMENT_ORDER)) {
				if (assessmentLayout.getVisibility() == View.GONE) {
					String oId = (String) intent.getSerializableExtra(BroadcastConstant.ORDER_OID);
					String sId = (String) intent.getSerializableExtra(BroadcastConstant.SHOP_SID);
					assessmentLayout.show(sId, oId);

				} else {
					assessmentLayout.setVisibility(View.GONE);
				}

			} else if (action.equals(BroadcastConstant.NOTIFY_ACT_CONFIRM_DELIVER)) {
				// 确认收货
				if (conReceivTimeOrder.getVisibility() == View.GONE) {
					String oId = (String) intent.getSerializableExtra(BroadcastConstant.ORDER_OID);
					long acceptTime = intent.getLongExtra(BroadcastConstant.ORDER_ACCEPT_TIME, 0);
					conReceivTimeOrder.show(acceptTime, oId);

				} else {
					conReceivTimeOrder.setVisibility(View.GONE);
					conReceivTimeOrder.clear();
				}

			}

		}

	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.myorder_back:
			backOperate();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean backOperate() {
		if (conReceivTimeOrder != null) {
			if (conReceivTimeOrder.getVisibility() == View.VISIBLE) {
				conReceivTimeOrder.setVisibility(View.GONE);
				conReceivTimeOrder.clear();
				return true;
			}
		}
		if (assessmentLayout != null) {
			if (assessmentLayout.getVisibility() == View.VISIBLE) {
				assessmentLayout.setVisibility(View.GONE);
				// assessmentLayout.clear();
				return true;
			}
		}
		mActController.exitActivity(originClassName);
		return true;
	}

}
